<?php
/*
	
*/
defined('BY_JYA') or exit('Access Denied');
global $_RQ,$_AR;
$_RQ['op']=$_RQ['op']?$_RQ['op']:'main';
if($_RQ['op']=='main'){
	//查询在进行的项目
	$rid = intval($_RQ['rid']);
	$post=array();
	if(intval($_RQ['id'])){
		$post=pdo_get('jy_kabao_order',array('id'=>intval($_RQ['id']),'uniacid'=>$_SESSION['uniacid']));
		$post['jiangs']=json_decode($post['jiangs'],true);
	}else{
		$post['hdp']=array();
		$post['jiangs']=array();
	}
	$return['post']=$post;
	$return['list']=$list;
	$return['credit_types']=credit_types();
	$credit_rates=array();
	$setting=uni_setting('pay');
	foreach($return['credit_types'] as $k=>$v){
		$credit_rates[$k]=$setting['credit'.$k.'_rate']?:1;
	}
	$return['credit_rates']=$credit_rates;
	set_html('title','DIY礼包');
	exi($return);
}
if($_RQ['op']=='post'){
	$postdata=get_postdata();
	if(empty($postdata['title'])){
		exi('礼包名称不能为空！','error');
	}
	if(empty($postdata['image'])){
		//exi('活动封面图不能为空！','error');
	}
	$jiangs=$postdata['jiangs'];
	$setting=uni_setting('pay');
	$oneprice=0;
	foreach($jiangs as $k=>$v){
		if($v['type']==0){
			$v['total']=$v['total']?:1;
			$goodsfee=$v['price']*$v['total'];
			$oneprice +=$goodsfee;
		}elseif($v['type']==2){
			$oneprice +=$v['num'];
		}elseif($v['type']==3){
			$setting['credit'.$v['credit_type'].'_rate']=$setting['credit'.$v['credit_type'].'_rate']?:1;
			$oneprice +=$v['num']/$setting['credit'.$v['credit_type'].'_rate'];
		}
	}
	$totalprice=$postdata['total']*$oneprice;
	$id=model('jy_kabao/order')->add_diyorder($postdata,$oneprice,$totalprice);
	if($totalprice>0){
			$params=array(
					'id'=>$id,
					'title'=>'购买DIY礼包订单',
					'fee'=>$totalprice,
					'plugin'=>'jy_shoplibao',
					//'pay_type'=>'wechat',//可选，此项作用为指定支付方式
					'no_type'=>array('hdfk'),//可选，此项作用为指定不允许使用哪种支付方式
					'back_url'=>'jy_shoplibao/diybao/payresult/',//必填，指定异步支付结果通知地址，采用系统标准URL书写格式
					'success_url'=>'jy_shoplibao/orderlist/',
					'error_url'=>'jy_shoplibao/orderlist/',
			);
			$payid=cfc('pay')->create_pay_order($params);
			pdo_update('jy_kabao_order',array('uniacid'=>$_SESSION['uniacid'],'pay_id'=>$payid),array('id'=>$id));
			$res=array(
				'pay_id'=>$payid,
				'order_id'=>$id,
			);
			exi($res);
	}else{
		pdo_update('jy_kabao_order',array('status'=>0),array('uniacid'=>$_SESSION['uniacid'],'id'=>$id));	
		exi('购买成功！','','jy_shoplibao/orderlist/');
	}
}
if($_RQ['op']=='payresult'){
	$payresult=$_SESSION['pay_result'];
	if(!$payresult){
		exi('支付失败，未收到支付结果！','error','main');
	}
	if($payresult['status']!=1){
		exi('支付失败！','error','main');
	}
	$order=pdo_get('jy_kabao_order',array('id'=>$payresult['id'],'uniacid'=>$_SESSION['uniacid']));
	if(!$order){
		exi('支付失败！指定订单不存在！','error');
	}
	if(!$order['status']){
		exi('订单已支付，无需重复支付！','error');
	}
	if($order['payfee']!=$payresult['fee']){
		exi('支付失败！订单金额不匹配！','error');
	}
	pdo_update('jy_kabao_order',array('status'=>0),array('uniacid'=>$_SESSION['uniacid'],'id'=>$payresult['id']));	
	exi('支付成功','success','jy_shoplibao/orderlist/');
}